package com.sright.bcard.user.biz.manager.impl;

import com.alibaba.fastjson.JSON;
import com.sright.bcard.common.service.share.dto.LoginUser;
import com.sright.bcard.common.service.share.dto.page.PageDTO;
import com.sright.bcard.common.service.share.dto.page.PageParamRequest;
import com.sright.bcard.common.service.share.dto.pager.Pager;
import com.sright.bcard.common.service.share.dto.request.VisitorPageRequest;
import com.sright.bcard.common.service.share.dto.response.VisitorDataResponse;
import com.sright.bcard.common.service.share.dto.response.VisitorPageResponse;
import com.sright.bcard.common.service.share.dto.response.VisitorRelationshipResponse;
import com.sright.bcard.common.service.share.dto.user.VisitorAnalysisDTO;
import com.sright.bcard.common.service.share.exception.base.BusinessErrorException;
import com.sright.bcard.common.service.share.exception.code.BusinessCode;
import com.sright.bcard.common.service.share.utils.DataConvertUtils;
import com.sright.bcard.common.service.share.utils.DateTimeUtils;
import com.sright.bcard.common.service.share.utils.IpUtils;
import com.sright.bcard.common.share.service.WxappService;
import com.sright.bcard.content.dal.dao.*;
import com.sright.bcard.content.dal.entity.*;
import com.sright.bcard.user.dal.entity.ext.VisitorEXTDO;
import com.sright.bcard.user.dal.entity.ext.VisitorRelationEXTDO;
import com.sright.bcard.user.share.request.AnalysisListParam;
import com.sright.bcard.user.biz.manager.VisitorManager;
import com.sright.bcard.user.dal.dao.*;
import com.sright.bcard.user.dal.entity.*;
import com.sright.bcard.user.dal.query.AnalysisListParamQuery;
import com.sright.bcard.common.service.share.dto.user.VisitorOverviewDTO;
import com.sright.bcard.common.service.share.dto.user.VisitorRankingDTO;
import com.sright.bcard.user.share.request.AddVisitorParamRequest;
import com.sright.bcard.user.share.response.AnalysisListResponse;
import com.sright.common.response.SrightResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author peter
 * @description
 * @date 2020/6/3
 */
@Component
@Slf4j
public class VisitorManagerImpl implements VisitorManager {

    @Autowired
    private VisitorAnalysisDAO visitorAnalysisDAO;

    @Autowired
    private VisitorDAO visitorDAO;

    @Autowired
    private VisitorListDAO visitorListDAO;

    @Autowired
    private CardDAO cardDAO;

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private DataCardVisitNumDAO dataCardVisitNumDAO;

    @Autowired
    private MemberDAO memberDAO;

    @Autowired
    private DataTemplateVisitNumDAO dataTemplate;

    @Autowired
    private CardBaseInfoDAO cardBaseInfoDAO;

    @Autowired
    private VisitorStatisticsDAO visitorStatisticsDAO;

    @Autowired
    private VisitorDateDAO visitorDateDAO;

    @Autowired
    private CardSettingDAO cardSettingDAO;

    @Autowired
    private WxappService wxappService;

    @Autowired
    private UserTagsDAO userTagsDAO;

    @Autowired
    private TagLibraryDAO tagLibraryDAO;

    @Autowired
    private CardUserInfoDAO cardUserInfoDAO;

    private static String LAST_VISTOR_AT = "last_vistor_at";

    private static String TOTAL = "total";

    private static String AVATAR_TEMP_1 = "https://ergeng-static.oss-cn-hangzhou.aliyuncs.com/card/%E9%80%9A%E8%AE%AF%E5%BD%95%402x.png";

    private static String AVATAR_TEMP_2 = "https://ergeng-static.oss-cn-hangzhou.aliyuncs.com/card/%E4%BC%81%E4%B8%9A%E6%88%90%E5%91%98%402x.png";

    private static String A = "a";

    private static String B = "b";

    @Autowired
    private DataCardShareNumDAO dataCardShareNumDAO;

    @Override
    public SrightResponse getVisitorRanking(LoginUser loginUser) {
        Long enterpriseId = loginUser.getEnterpriseId();
        if (enterpriseId == null) {
            return SrightResponse.defaultRequestError("企业状态异常");
        }

        List<VisitorAnalysisDO> analysisDOList = visitorAnalysisDAO.selectByEnterpriseId(enterpriseId);
        if (analysisDOList == null || analysisDOList.size() == 0) {
            return SrightResponse.defaultSuccess(new ArrayList<>());
        }

        List<VisitorRankingDTO> result = new ArrayList<>();
        for (VisitorAnalysisDO visitorAnalysisDO : analysisDOList) {
            VisitorRankingDTO visitorRankingDTO = new VisitorRankingDTO();
            visitorRankingDTO.setId(visitorAnalysisDO.getId());
            visitorRankingDTO.setMemberId(visitorAnalysisDO.getVisitorMemberId());
            visitorRankingDTO.setNickname(visitorAnalysisDO.getName());
            visitorRankingDTO.setAvatar(visitorAnalysisDO.getAvatar());
            visitorRankingDTO.setLengthStay(visitorAnalysisDO.getLengthVisit() / 60);

            List<VisitorDO> visitorDOList = visitorDAO.selectByEnterpriseIdAndMemberId(enterpriseId,
                    visitorAnalysisDO.getVisitorMemberId());
            Integer total = 0;
            for (VisitorDO visitorDO : visitorDOList) {
                total += Integer.valueOf(visitorDO.getTotal());
            }
            visitorRankingDTO.setNumVisits(total);
            result.add(visitorRankingDTO);
        }

        List<VisitorRankingDTO> sortedList =
                result.stream().sorted(Comparator.comparing(VisitorRankingDTO::getNumVisits).reversed()).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(sortedList)) {
            for (int i = 0; i < sortedList.size(); i ++ ) {
                long rank = i + 1;
                sortedList.get(i).setId(rank);
            }
            return SrightResponse.defaultSuccess(sortedList);
        }
        return SrightResponse.defaultSuccess(new ArrayList<>());
    }

    @Override
    public SrightResponse getVisitorOverview(LoginUser loginUser) {
        Long enterpriseId = loginUser.getEnterpriseId();
        if (enterpriseId == null) {
            return SrightResponse.defaultRequestError("企业状态异常");
        }

        VisitorOverviewDTO visitorOverviewDTO = new VisitorOverviewDTO();
        try {
            //访客总数
            List<VisitorAnalysisDO> visitorAnalysisDOList = visitorAnalysisDAO.selectByEnterpriseId(enterpriseId);
            if (CollectionUtils.isNotEmpty(visitorAnalysisDOList)) {
                visitorOverviewDTO.setVisitorNumber(visitorAnalysisDOList.size());
            } else {
                visitorOverviewDTO.setVisitorNumber(0);
            }

            //访问总次数
            Integer visitTime = visitorDAO.selectSumTotalByEnterpriseId(enterpriseId);
            visitorOverviewDTO.setVisitTime(visitTime == null ? 0 : visitTime);

            //员工总数
            List<UserDO> userDOList = userDAO.selectByEnterpriseId(enterpriseId);
            if (CollectionUtils.isNotEmpty(userDOList)) {
                visitorOverviewDTO.setUserNumber(userDOList.size());
            } else {
                visitorOverviewDTO.setUserNumber(0);
            }
            //已绑定微信员工数
            Integer bindUserNum = Math.toIntExact(userDAO.selectBindUserNumById(enterpriseId));
            visitorOverviewDTO.setBindUserNumber(bindUserNum);
            //分享总次数
            List<Long> userIdList = new LinkedList<>();
            for (UserDO userDO : userDOList) {
                userIdList.add(userDO.getId());
            }
            Integer shareNum = dataCardShareNumDAO.selectSumByUserList(userIdList);
            visitorOverviewDTO.setShareNumber(shareNum == null ? 0 : shareNum);
            //分享总人数
            Integer shareUserNum = dataCardShareNumDAO.selectCountByUserList(userIdList);
            visitorOverviewDTO.setShareUserNumber(shareUserNum);
        } catch (Throwable throwable) {
            log.error("error : {}", throwable);
        }

        return SrightResponse.defaultSuccess(visitorOverviewDTO);
    }

    @Override
    public VisitorDataResponse parentRelationship(Long id) {
        VisitorDataResponse visitorDataResponse = new VisitorDataResponse();
        // 根据id查询访客关联分析
        VisitorAnalysisDO visitorAnalysisDO = visitorAnalysisDAO.selectById(id);
        if(null != visitorAnalysisDO) {
            VisitorAnalysisDTO visitorAnalysisDTO = DataConvertUtils.convertDO2DTO(visitorAnalysisDO, VisitorAnalysisDTO.class);
            // 上级-我访问过的
            List<VisitorRelationEXTDO> visitorListDOS = visitorListDAO.selectByMemberId(visitorAnalysisDO.getVisitorMemberId());
            List<VisitorRelationshipResponse> visitorRelationshipResponses = buildResponse(visitorListDOS);
            visitorDataResponse.setVisitorAnalysisDTO(visitorAnalysisDTO);
            visitorDataResponse.setVisitorRelationshipResponses(visitorRelationshipResponses);
        }
        return visitorDataResponse;
    }

    @Override
    public VisitorDataResponse childrenRelationship(Long id) {
        VisitorDataResponse visitorDataResponse = new VisitorDataResponse();
        // 根据id查询访客关联分析
        VisitorAnalysisDO visitorAnalysisDO = visitorAnalysisDAO.selectById(id);
        if(null != visitorAnalysisDO) {
            VisitorAnalysisDTO visitorAnalysisDTO = DataConvertUtils.convertDO2DTO(visitorAnalysisDO, VisitorAnalysisDTO.class);
            // 下级-访问过我的
            List<VisitorRelationshipResponse> visitorRelationshipResponses = new LinkedList<>();
            List<UserDO> userDOList = userDAO.selectAllUserByMemberId(visitorAnalysisDO.getVisitorMemberId());
            if (CollectionUtils.isNotEmpty(userDOList)) {
                List<Long> userIdList = new LinkedList<>();
                for (UserDO userDO : userDOList) {
                    userIdList.add(userDO.getId());
                }
                List<VisitorRelationEXTDO> visitorListDOS = visitorListDAO.selectByUserId(userIdList);
                visitorRelationshipResponses = buildResponse(visitorListDOS);
            }
            visitorDataResponse.setVisitorAnalysisDTO(visitorAnalysisDTO);
            visitorDataResponse.setVisitorRelationshipResponses(visitorRelationshipResponses);
        }
        return visitorDataResponse;
    }

    private List<VisitorRelationshipResponse> buildResponse(List<VisitorRelationEXTDO> visitorListDOS) {
        List<VisitorRelationshipResponse> visitorRelationshipResponses = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(visitorListDOS)) {
            visitorListDOS.stream().forEach(visitorListDO -> {
                VisitorRelationshipResponse visitorRelationshipResponse = new VisitorRelationshipResponse();
                visitorRelationshipResponse.setId(visitorListDO.getMemberId());
                visitorRelationshipResponse.setName(visitorListDO.getName());
                visitorRelationshipResponse.setAvatar(visitorListDO.getAvatar());
                visitorRelationshipResponses.add(visitorRelationshipResponse);
            });
        }
        return visitorRelationshipResponses;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Long addVisitor(AddVisitorParamRequest addVisitorParamRequest, HttpServletRequest request) throws Exception {
        CardDO cardDO = cardDAO.selectById(addVisitorParamRequest.getCardId());
        if (cardDO == null) {
            throw new BusinessErrorException(BusinessCode.CARD_INFO_NOT_EXSIT);
        }
        UserDO userDO = userDAO.selectById(addVisitorParamRequest.getCardUserId());
        MemberDO memberDO = memberDAO.selectById(addVisitorParamRequest.getMemberId());

        long parentId = 0L;
        if (addVisitorParamRequest.getRelation() != null && !addVisitorParamRequest.getRelation().equals("")) {
            String[] relationArray = addVisitorParamRequest.getRelation().split("-");
            String lastRecordId = relationArray[relationArray.length - 1];
            if (!lastRecordId.equals("a") && !lastRecordId.equals("b")) {
                parentId = Long.parseLong(lastRecordId);
                VisitorListDO lastVisitorList = visitorListDAO.selectById(Long.valueOf(lastRecordId));
                if (lastVisitorList.getVisitorMemberId().equals(addVisitorParamRequest.getMemberId())) {
                    //如果自己访问自己分享的名片，不增加访客信息
                    SrightResponse.defaultSuccess();
                }
            }
        }

        VisitorDO visitorDO = visitorDAO.selectByUserIdAndCardId(addVisitorParamRequest.getCardUserId(),addVisitorParamRequest.getMemberId());

        if (userDO.getMemberId().equals(addVisitorParamRequest.getMemberId())) {
            if (addVisitorParamRequest.getRelation().equals("") || addVisitorParamRequest.getRelation()== null) {
                if (visitorDO != null) {
                    List<VisitorListDO> visitorListDOS = visitorListDAO.selectByVisitorId(visitorDO.getId());
                    if (CollectionUtils.isNotEmpty(visitorListDOS)) {
                        SrightResponse.defaultSuccess();
                    }
                }
            }
        } else {
            //增加名片访问统计记录
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            String dateStr = simpleDateFormat2.format(date) + " 00:00:00";
            Date today = simpleDateFormat.parse(dateStr);

            DataCardVisitNumDO dataCardVisitNumDO = dataCardVisitNumDAO.selectByToday(addVisitorParamRequest.getCardId(),addVisitorParamRequest.getCardUserId(),today);
            if (dataCardVisitNumDO == null) {
                DataCardVisitNumDO insertData = new DataCardVisitNumDO();
                insertData.setCardId(addVisitorParamRequest.getCardId());
                insertData.setNum(1);
                insertData.setUserId(
                        addVisitorParamRequest.getCardUserId());
                dataCardVisitNumDAO.insert(insertData);
            } else {
                dataCardVisitNumDO.setNum(dataCardVisitNumDO.getNum() + 1);
                dataCardVisitNumDAO.updateSelective(dataCardVisitNumDO);
            }

            //统计模板数据
            CardBaseInfoDO cardBaseInfoDO = cardBaseInfoDAO.selectById(cardDO.getBaseInfoId());
            DataTemplateVisitNumDO dataTemplateVisitNumDO = dataTemplate.selectByMmeberIdAndTemplateId(addVisitorParamRequest.getMemberId(),cardBaseInfoDO.getTemplateId());
            if (dataTemplateVisitNumDO == null) {
                dataTemplateVisitNumDO = new DataTemplateVisitNumDO();
                dataTemplateVisitNumDO.setMemberId(addVisitorParamRequest.getMemberId());
                dataTemplateVisitNumDO.setTemplateId(cardBaseInfoDO.getTemplateId());
                dataTemplateVisitNumDO.setVisitCount(1);
                dataTemplate.insert(dataTemplateVisitNumDO);
            } else {
                dataTemplateVisitNumDO.setVisitCount(dataTemplateVisitNumDO.getVisitCount() + 1);
                dataTemplate.updateAll(dataTemplateVisitNumDO);
            }
        }

        //生成访客数据
        Long visitorId;
        if (visitorDO != null) {
            visitorDO.setNickname(memberDO.getNickname());
            visitorDO.setAvatar(memberDO.getAvatarLocal());
            visitorDO.setMobile(memberDO.getMobile());
            visitorDO.setVisitorMemberId(addVisitorParamRequest.getMemberId());
            visitorDO.setTotal(visitorDO.getTotal() + 1);
            visitorDO.setLastVistorAt(new Date());
            visitorDAO.updateAll(visitorDO);

            visitorId = visitorDO.getId();
        } else {
            visitorDO = new VisitorDO();
            visitorDO.setNickname(memberDO.getNickname());
            visitorDO.setAvatar(memberDO.getAvatarLocal());
            visitorDO.setMobile(memberDO.getMobile());
            visitorDO.setVisitorMemberId(addVisitorParamRequest.getMemberId());
            visitorDO.setUserId(addVisitorParamRequest.getCardUserId());
            visitorDO.setCardId(addVisitorParamRequest.getCardId());
            visitorDO.setTotal(1);
            visitorDO.setLastVistorAt(new Date());
            visitorId = visitorDAO.insertSelective(visitorDO);
        }

        //生成visitorList记录
        VisitorListDO visitorListDO = new VisitorListDO();
        visitorListDO.setEnterpriseId(userDO.getEnterpriseId());
        visitorListDO.setUserId(addVisitorParamRequest.getCardUserId());
        visitorListDO.setCardId(addVisitorParamRequest.getCardId());
        visitorListDO.setVisitorId(visitorId);
        visitorListDO.setVisitorMemberId(addVisitorParamRequest.getMemberId());
        visitorListDO.setParentId(parentId);
        visitorListDO.setIp(IpUtils.getIpAddress(request));
        if (addVisitorParamRequest.getSourceId() != null) {
            visitorListDO.setSourceId(addVisitorParamRequest.getSourceId());
        }
        if (addVisitorParamRequest.getRelation() != null) {
            visitorListDO.setRelation(addVisitorParamRequest.getRelation());
        }
        Long recordId = visitorListDAO.insertSelective(visitorListDO);

        if (userDO.getEnterpriseId() > 0) {
            Long visitorDateId;
            //访问企业名片还需增加 VisitorDate VisitorStatistic VisitorAnalysis表的数据
            VisitorDateDO visitorDateDO = new VisitorDateDO();
            visitorDateDO.setEnterpriseId(userDO.getEnterpriseId());
            visitorDateDO.setUserId(userDO.getId());
            visitorDateDO.setMemberId(userDO.getMemberId());
            visitorDateDO.setType(1);
            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
            visitorDateDO.setToday(formatter.parse(formatter.format(new Date())));
            VisitorDateDO visitorDateDO1 = visitorDateDAO.selectByObject(visitorDateDO);
            if (visitorDateDO1 == null) {
                visitorDateDO.setTotal(1);
                visitorDateId = visitorDateDAO.insertSelective(visitorDateDO);
            } else {
                visitorDateDO1.setTotal(visitorDateDO1.getTotal() + 1);
                visitorDateId = visitorDateDO1.getId();
            }

            VisitorStatisticsDO visitorStatisticsDO = new VisitorStatisticsDO();
            visitorStatisticsDO.setEnterpriseId(userDO.getEnterpriseId());
            visitorStatisticsDO.setToUserId(userDO.getId());
            visitorStatisticsDO.setVisitorDataId(visitorDateId);
            visitorStatisticsDO.setVisitorUserId(addVisitorParamRequest.getVisitorEnterpriseUserId());
            visitorStatisticsDO.setVisitorMemberId(addVisitorParamRequest.getMemberId());
            visitorStatisticsDO.setNickname(memberDO.getNickname());
            visitorStatisticsDO.setAvatar(memberDO.getAvatarLocal());
            visitorStatisticsDO.setType(1);
            visitorStatisticsDO.setIp(IpUtils.getIpAddress(request));
            visitorStatisticsDAO.insertSelective(visitorStatisticsDO);

            if (!userDO.getMemberId().equals(addVisitorParamRequest.getMemberId())) {
                VisitorAnalysisDO visitorAnalysisDO = visitorAnalysisDAO.selectByMemberIdAndEnterpriseId(addVisitorParamRequest.getMemberId(),userDO.getEnterpriseId());
                if (visitorAnalysisDO == null) {
                    visitorAnalysisDO = new VisitorAnalysisDO();
                    visitorAnalysisDO.setEnterpriseId(userDO.getEnterpriseId());
                    visitorAnalysisDO.setVisitorMemberId(addVisitorParamRequest.getMemberId());
                    visitorAnalysisDO.setName(memberDO.getNickname());
                    visitorAnalysisDO.setAvatar(memberDO.getAvatarLocal());
                    visitorAnalysisDO.setMobile(memberDO.getMobile());

                    CardUserInfoDO cardUserInfoDO = cardUserInfoDAO.selectOneByUserId(userDO.getId());
                    visitorAnalysisDO.setFirstName(cardUserInfoDO.getName());
                    visitorAnalysisDO.setFirstVistorAt(new Date());
                    visitorAnalysisDO.setLastVistorAt(new Date());
                    visitorAnalysisDAO.insertSelective(visitorAnalysisDO);
                } else {
                    visitorAnalysisDO.setLastVistorAt(new Date());
                    visitorAnalysisDO.setName(memberDO.getNickname());
                    visitorAnalysisDO.setAvatar(memberDO.getAvatarLocal());
                    visitorAnalysisDO.setMobile(memberDO.getMobile());
                    visitorAnalysisDAO.updateSelective(visitorAnalysisDO);
                }
            }
        }

        //访客提醒推送
        if (!userDO.getMemberId().equals(addVisitorParamRequest.getMemberId())) {
            pushVisitorMsg(userDO,memberDO.getNickname(),parentId);
        }

        return recordId;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean recordAccessTime(Long recordId, Integer time) {
        VisitorListDO visitorListDO = visitorListDAO.selectById(recordId);
        if (visitorListDO == null) {
            throw new BusinessErrorException(BusinessCode.VISITOR_RECORD_NOT_EXSIT);
        }
        visitorListDO.setTime(time);
        Boolean result = visitorListDAO.updateSelective(visitorListDO);
        if(!result) {
            throw new BusinessErrorException(BusinessCode.SYS_ERROR);
        }

        //更新visitorAnalysis 表
        VisitorAnalysisDO visitorAnalysisDO = visitorAnalysisDAO.selectByMemberIdAndEnterpriseId(visitorListDO.getVisitorMemberId(),visitorListDO.getEnterpriseId());
        if (visitorAnalysisDO != null) {
            visitorAnalysisDO.setLastVistorAt(new Date());
            visitorAnalysisDO.setLengthVisit(visitorAnalysisDO.getLengthVisit() + time);
            return visitorAnalysisDAO.updateSelective(visitorAnalysisDO);
        }
        return false;
    }

    @Override
    public Pager<VisitorPageResponse> pageVisitorList(VisitorPageRequest visitorPageRequest) {
        List<VisitorPageResponse> visitorPageResponseList = new ArrayList<>();

        PageParamRequest paramRequest = new PageParamRequest();
        Integer offset = (visitorPageRequest.getPage() - 1) * visitorPageRequest.getPageSize();
        paramRequest.setOffset(offset);
        paramRequest.setLimit(visitorPageRequest.getPageSize());

        List<VisitorDO> visitorDOList;

        String order = LAST_VISTOR_AT;
        if (visitorPageRequest.getType() == 3 || visitorPageRequest.getType() == 1) {
            if (visitorPageRequest.getType() == 3) {
                order = TOTAL;
            }

            //去除掉我自己的访客
            UserDO myInfo = userDAO.selectById(visitorPageRequest.getUserId());
            visitorDOList = visitorDAO.selectPageData(paramRequest,visitorPageRequest.getUserId(),order,myInfo.getMemberId());
            if (visitorDOList == null || visitorDOList.size() == 0) {
                Pager result = new Pager(visitorPageRequest.getPage(),visitorPageRequest.getPageSize(),0,visitorDOList);
                return result;
            }
        } else {
            List<VisitorDO> newVisitorDOList = getVisitorListByTime(visitorPageRequest);
            if (newVisitorDOList.size() > visitorPageRequest.getPageSize()) {
                visitorDOList = newVisitorDOList.subList(offset,visitorPageRequest.getPageSize());
            } else {
                visitorDOList = newVisitorDOList;
            }
        }

        for (VisitorDO visitorDO : visitorDOList) {
            VisitorPageResponse visitorPageResponse = new VisitorPageResponse();
            Integer time = visitorListDAO.selectSumTimeByVisitorId(visitorDO.getId());
            if (time == null) {
                time = 0;
            }
            List<VisitorPageResponse.Relation> relationList = new ArrayList<>();

            List<VisitorListDO> visitorListDOList = visitorListDAO.selectAllByVisitorId(visitorDO.getId());
            if (visitorListDOList != null && visitorListDOList.size() > 0) {
                String relationString = visitorListDOList.get(visitorListDOList.size() - 1).getRelation();
                if (relationString != null && !relationString.equals("")) {
                    String[] relationArr = relationString.split("-");
                    for (String relationId : relationArr) {
                        VisitorPageResponse.Relation relation = new VisitorPageResponse.Relation();
                        if (relationId.equals(A)) {
                            relation.setMemberId(0L);
                            relation.setAvatar(AVATAR_TEMP_1);
                        } else if (relationId.equals(B)) {
                            relation.setMemberId(0L);
                            relation.setAvatar(AVATAR_TEMP_2);
                        } else {
                            VisitorListDO visitorListDO = visitorListDAO.selectById(Long.valueOf(relationId));
                            MemberDO memberDO = memberDAO.selectById(visitorListDO.getVisitorMemberId());
                            relation.setMemberId(visitorListDO.getVisitorMemberId());
                            relation.setAvatar(memberDO.getAvatarLocal());
                        }

                        relationList.add(relation);
                    }
                }
            }

            visitorPageResponse.setNickname(visitorDO.getNickname());
            visitorPageResponse.setAvatar(visitorDO.getAvatar());
            visitorPageResponse.setUserId(visitorDO.getUserId());
            visitorPageResponse.setMobile(visitorDO.getMobile());
            visitorPageResponse.setVisitorMemberId(visitorDO.getVisitorMemberId());
            visitorPageResponse.setLastVistorAt(visitorDO.getLastVistorAt());
            MemberDO memberDO = memberDAO.selectById(visitorDO.getVisitorMemberId());
            List<UserDO> userDOS = userDAO.selectVerifyUser(memberDO.getId());
            if (userDOS != null) {
                for (UserDO userDO : userDOS) {
                    if (userDO.getEnterpriseId() > 0) {
                        visitorPageResponse.setVisitorEnterpriseUserId(userDO.getId());
                    } else {
                        visitorPageResponse.setVisitorPersonalUserId(userDO.getId());
                    }
                }
            }
            visitorPageResponse.setTotal(visitorDO.getTotal());
            visitorPageResponse.setTime(time);
            visitorPageResponse.setRelation(relationList);

            visitorPageResponseList.add(visitorPageResponse);
        }

        Integer count = visitorDAO.selectCount(visitorPageRequest.getUserId());

        Pager<VisitorPageResponse> result = new Pager
                (visitorPageRequest.getPage(),visitorPageRequest.getPageSize(),count,visitorPageResponseList);
        return result;
    }

    public List<VisitorDO> getVisitorListByTime (VisitorPageRequest visitorPageRequest) {
        List<VisitorEXTDO> visitorEXTDOList = new ArrayList<>();
        UserDO myInfo = userDAO.selectById(visitorPageRequest.getUserId());
        List<VisitorDO> visitorDOList = visitorDAO.selectAllData(visitorPageRequest.getUserId(),myInfo.getMemberId());

        DataConvertUtils.convertDOList2DTOList(visitorDOList,visitorEXTDOList,VisitorEXTDO.class);

        for (VisitorEXTDO visitorEXTDO : visitorEXTDOList) {
            Integer time = visitorListDAO.selectSumTimeByVisitorId(visitorEXTDO.getId());
            if (time == null) {
                time = 0;
            }
            visitorEXTDO.setTime(time);
        }

        visitorEXTDOList.sort((x, y) -> Double.compare(y.getTime(),x.getTime()));

        List<VisitorDO> newVisitorDOList = new ArrayList<>();
        DataConvertUtils.convertDOList2DTOList(visitorEXTDOList,newVisitorDOList,VisitorDO.class);

        return newVisitorDOList;
    }

    @Override
    public SrightResponse visitorAnalysisList(AnalysisListParam analysisListParam) {
        log.info("visitorAnalysisList info : {}", JSON.toJSONString(analysisListParam));
        PageDTO<AnalysisListResponse> pageDTO = new PageDTO<>();
        if(null != analysisListParam) {
            AnalysisListParamQuery analysisListParamQuery = DataConvertUtils.
                    convertDO2DTO(analysisListParam, AnalysisListParamQuery.class);
            if (StringUtils.isNotEmpty(analysisListParam.getTags())) {
                analysisListParamQuery.setAnalysisIdList(Arrays.stream(analysisListParam.getTags().split(","))
                        .map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList()));
            }
            List<VisitorAnalysisDO> analysisListResultList = visitorAnalysisDAO.selectPageList(analysisListParamQuery);
            List<AnalysisListResponse> analysisListResponseList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(analysisListResultList)) {
                DataConvertUtils.convertDOList2DTOList(analysisListResultList,analysisListResponseList,AnalysisListResponse.class);
                for (AnalysisListResponse analysisListResponse : analysisListResponseList) {
                    List<UserTagsDO> userTagsDOList = userTagsDAO.selectByAnalysisId(analysisListResponse.getId());
                    List<AnalysisListResponse.TagsBean> tagsBeanList = new LinkedList<>();
                    if (CollectionUtils.isNotEmpty(userTagsDOList)) {
                        List<Long> userTagIdList = new LinkedList<>();
                        for(UserTagsDO userTagsDO : userTagsDOList) {
                            userTagIdList.add(userTagsDO.getTagId());
                        }

                        List<TagLibraryDO> tagLibraryDOList = tagLibraryDAO.selectByIds(userTagIdList);
                        if (CollectionUtils.isNotEmpty(tagLibraryDOList)) {
                            DataConvertUtils.convertDOList2DTOList(tagLibraryDOList,tagsBeanList,AnalysisListResponse.TagsBean.class);
                        }
                    }
                    analysisListResponse.setTags(tagsBeanList);
                    if (analysisListResponse.getLengthVisit() == 0) {
                        analysisListResponse.setLengthVisit(1);
                    }
                    if (analysisListResponse.getMobile() == null) {
                        analysisListResponse.setMobile("");
                    }
                }
            }

            Integer count = visitorAnalysisDAO.count(analysisListParamQuery);
            pageDTO.setCount(count);
            pageDTO.setData(analysisListResponseList);
        }
        return SrightResponse.defaultSuccess(pageDTO);
    }

    @Override
    public void dataPushDay() throws Exception {
        List<MemberDO> memberDOList = memberDAO.selectAll();
        if (CollectionUtils.isNotEmpty(memberDOList)) {
            for (MemberDO memberDO : memberDOList) {
                if (StringUtils.isNotEmpty(memberDO.getOpenid())) {
                    List<UserDO> userDOList = userDAO.selectAllUserByMemberId(memberDO.getId());
                    if(CollectionUtils.isNotEmpty(userDOList)) {
                        for (UserDO userDO : userDOList) {
                            CardSettingDO cardSettingDO = cardSettingDAO.selectByUserId(userDO.getId());
                            if (cardSettingDO != null && cardSettingDO.getVisitorDataPush() == 1) {
                                Map<String ,Integer> dataMap = getDayVisitorDataByUserId(userDO.getId());
                                if (dataMap.get("visitorCount") > 0 || dataMap.get("viewCount") > 0) {
                                    String userType = userDO.getEnterpriseId() > 0 ? "1" : "2";
                                    String countString = dataMap.get("viewCount") + "次/" + dataMap.get("visitorCount") + "人";
                                    Map<String,String> map = new HashMap<>();
                                    map.put("openid",memberDO.getOpenid());
                                    map.put("userType",userType);
                                    map.put("countString",countString);
                                    wxappService.sendDataStatisticsTemplateMessage(map);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    protected Map<String ,Integer> getDayVisitorDataByUserId(Long userId) {
        //计算访客量
        String now = DateTimeUtils.formatString(new Date(),DateTimeUtils.DATA_FORMAT_yyyy_MM_dd);

        Date beginDate = DateTimeUtils.formatDate(now + " 00:00:00",DateTimeUtils.DATE_TIME_STYLE);
        Date endDate = DateTimeUtils.formatDate(now + " 23:59:59",DateTimeUtils.DATE_TIME_STYLE);
        Integer visitorCount = visitorDAO.selectCountBetweenDate(userId,beginDate,endDate);
        Integer viewCount = dataCardVisitNumDAO.selectSumByDate(userId,beginDate);

        Map<String ,Integer> map = new HashMap<>();
        map.put("visitorCount",visitorCount);
        map.put("viewCount",viewCount);
        return map;
    }

    /**
     *
     * @param user 被推送人信息
     * @param visitorNickname 访客昵称
     * @param parentId 上级记录ID
     * @return
     * @throws Exception
     */
    public Boolean pushVisitorMsg (UserDO user,String visitorNickname,Long parentId) throws Exception {
        CardSettingDO cardSettingDO = cardSettingDAO.selectByUserId(user.getId());
        if (cardSettingDO != null) {
            //获取用户openID
            MemberDO memberDO = memberDAO.selectById(user.getMemberId());
            if (memberDO != null && !memberDO.getOpenid().equals("")) {
                //获取访问上级名称
                String parentNickname = "直接访问";
                if (parentId > 0) {
                    VisitorListDO visitorListDO = visitorListDAO.selectById(parentId);
                    MemberDO parentMember = memberDAO.selectById(visitorListDO.getVisitorMemberId());
                    parentNickname = parentMember.getNickname();
                }

                //拼接推送数据
                Map<String,String> map = new HashMap<>();
                if (user.getEnterpriseId() > 0) {
                    map.put("userType","1");
                } else {
                    map.put("userType","2");
                }
                map.put("openid",memberDO.getOpenid());
                map.put("parentNickname",parentNickname);
                map.put("nickname",visitorNickname);

                wxappService.sendVisitorTemplateMessage(map);
            }
        }
        return true;
    }
}
